package org.finesys.common.netty.websocket.stomp.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.TooLongFrameException;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.List;

import static org.finesys.common.netty.websocket.constants.WebConfigConstant.MAX_FRAME_SIZE;

public class WebSocketFrameToByteBufDecoder extends MessageToMessageDecoder<TextWebSocketFrame> {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame, List<Object> list) throws Exception {
        ByteBuf byteBuf = textWebSocketFrame.content();
        int readAble = byteBuf.readableBytes();
        if (readAble > MAX_FRAME_SIZE.getValue()) {
            TooLongFrameException exception = new TooLongFrameException("WebSocket Frame length too large: " + readAble + " -" + " max size:" + MAX_FRAME_SIZE.getValue());
            throw exception;
        }
        list.add(byteBuf.retain());
    }
}
